#!/usr/bin/env bash

is_enabled () {
    echo "$1" | grep -q -i -E "^(yes|on|true|1)$"
}

is_disabled () {
    echo "$1" | grep -q -i -E "^(no|off|false|0)$"
}


WINE_BRANCH="${WINE_BRANCH:-stable}"
TIMESTAMP="$(date +"%Y%m%d")"
NO_RDP="${NO_RDP:-no}"

# Run container and extract wine version
WINE_VER="$(docker run -it --rm "${DOCKER_REPO}" /bin/bash -c "dpkg -s wine-${WINE_BRANCH} \
    | grep '^Version:\s' | awk '{print \$2}' | sed -E 's/~.*$//'" | tr -d "\r")"

if echo "${WINE_VER}" | grep -q -E "^[0-9]+(\.[0-9]+)*$"; then
    echo "Found wine version '${WINE_VER}'"
else
    echo "ERROR: Unable to determine wine version"
    exit 1
fi

# Append '-nordp' to the image tag only if NO_RDP is true
if is_enabled "${NO_RDP}"; then
    SUFFIX="-nordp"
elif is_disabled "${NO_RDP}"; then
    SUFFIX=""
else
    echo "ERROR: Invalid value '${NO_RDP}' used for NO_RDP"
    exit 1
fi

# Generate tags
docker tag "${DOCKER_REPO}" "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}${SUFFIX}"
docker tag "${DOCKER_REPO}" "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}-${WINE_VER}${SUFFIX}"
docker tag "${DOCKER_REPO}" "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}-${WINE_VER}-${TIMESTAMP}${SUFFIX}"

# Login to Docker Hub
echo "${DOCKER_PASSWORD}" | docker login -u "${DOCKER_USERNAME}" --password-stdin

# Push the image and tags
docker push "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}${SUFFIX}"
docker push "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}-${WINE_VER}${SUFFIX}"
docker push "${DOCKER_USERNAME}/${DOCKER_REPO}:${WINE_BRANCH}-${WINE_VER}-${TIMESTAMP}${SUFFIX}"

# Push the wine-stable image as latest tag
if [ "${WINE_BRANCH}" == "stable" ]; then
    docker tag "${DOCKER_REPO}" "${DOCKER_USERNAME}/${DOCKER_REPO}:latest${SUFFIX}"
    docker push "${DOCKER_USERNAME}/${DOCKER_REPO}:latest${SUFFIX}"
fi
